<?
function drizzo_gallery_get_the_folders($folder = '/drizzo-files/gallery') {
	$dir = root_dir . str_replace(drizzo_global_options('gallery_basename'),"drizzo-files/gallery",$folder);
	if(is_dir($dir) && $folder = opendir($dir)) {
		while(false !== ($file = readdir($folder))) {
			$contents[] = $file;
		}
		closedir($folder);
	}
	if(count($contents) > 0) {
		foreach($contents as $content) {
			if(is_dir($dir . "/" . $content) && $content != 'thumbs' && $content != 'cache' && $content{0} != '.' && $content != '') {
				$directories[] = $content;
			}
		}
	}
	return $directories;
}

function drizzo_gallery_get_the_images($folder = '/drizzo-files/gallery') {
	$dir = str_replace("//","/",root_dir . $folder);
	if(is_dir($dir)) {
		if($folder = opendir($dir)) {
			while(false !== ($file = readdir($folder))) {
				$contents[] = $file;
			}
			closedir($folder);
		}
	}
	if($contents) {
		foreach($contents as $content) {
			if(!is_dir($dir . "/" . $content)) {
				$files[] = $content;
			}
		}
	}
	if($files) {
		foreach($files as $file) {
			$extension = pathinfo($file);
			$extension = $extension['extension'];
			$image_types = array('jpg','jpeg','png','gif');
			if(in_array($extension, $image_types)) {
				$image_list[] = $file;
			}
		}
	}
	return $image_list;
}

function drizzo_gallery_is_image() {
	$dir = str_replace(drizzo_global_options('gallery_basename'),'drizzo-files/gallery',dirname($_SERVER['REQUEST_URI']));
	$extensions = array('.jpg','.jpeg','.png','.gif');
	foreach($extensions as $extension) {
		if(file_exists(str_replace("//","/",root_dir . $dir . "/" . basename($_SERVER['REQUEST_URI']) . $extension))) {
			return basename($_SERVER['REQUEST_URI']) . $extension;
		} else {
			$tries++;
		}
	}
	if($tries == count($extensions)) {
		return false;
	}
}

function drizzo_gallery_image() {
	global $drizzo_posts, $drizzo_comments, $drizzo_gallery;
	
	$path = pathinfo($_SERVER['REQUEST_URI']);
	$path['basename'] = $path['basename'];
	$local_path = str_replace(array("//",drizzo_global_options('gallery_basename')),array("/","drizzo-files/gallery"),root_dir . $path['dirname']);
	if(is_dir($local_path)) {
		$image = drizzo_gallery_is_image();
	}
	$local_image_path = $local_path . "/" . $image;
	if($image) {
		$file_name = $image;
		$cache_path = str_replace('gallery', 'gallery/cache', $local_path);
		$cache_image_path = $cache_path . "/" . $image;
		if(!file_exists($cache_path)) {
			$make_folder = drizzo_mkdir($cache_path);
		}
		if(!file_exists($cache_image_path)) {			
			if(is_writable($cache_path)) {
				list($width, $height, $type) = getimagesize($local_image_path);
				$new_width = 400;
				if($width > $height) {
					$ratio = $width/$height;
					$new_height = round(400/$ratio);
				} else {
					$ratio = $height/$width;
					$new_height = round(400*$ratio);
				}
				if($type == 2 || $type == 3) {
					$midsize = imagecreatetruecolor($new_width,$new_height);
					if($type == 2) {
						$original = imagecreatefromjpeg($local_image_path);
						imagecopyresampled($midsize, $original, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						$midsize_check = imagejpeg($midsize, $cache_image_path, 100);
					} else {
						$original = imagecreatefrompng($local_image_path);
						imagecopyresampled($midsize, $original, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						$midsize_check = imagepng($midsize, $cache_image_path, 100);
					}
					if($midsize_check) {
						$url_path = str_replace(root_dir, domain, $cache_image_path);
						$image = "<a href=\"" . str_replace('/cache','',$url_path) . "\" title=\"View Full Size\"><img src=\"" . $url_path . "\" alt=\"" . $image . "\" /></a>\n";
					}
					$title = drizzo_gallery_is_image();
					$timestamp = time();
					$image_insert = @mysql_query("INSERT INTO `$drizzo_posts` (`type`,`status`,`title`,`content`,`comment_status`,`posted_date`) VALUES('image','publish','$title','','open','$timestamp')");
					if(!mysql_errno()) {
						$post_id = mysql_insert_id();
						$image_insert_2 = @mysql_query("INSERT INTO `$drizzo_gallery` (`post_id`,`file_path`) VALUES('$post_id','$local_image_path')");
						$image_lookup = @mysql_query("SELECT `post_id` FROM `$drizzo_gallery` WHERE `file_path`='$local_image_path'");
						if(!mysql_errno()) {
							$url_path = str_replace(root_dir, '', $cache_image_path);
							$post_id = @mysql_fetch_assoc($image_lookup);
							$image = array(
								'ID' => $post_id['post_id'],
								'link' => "<a href=\"" . str_replace('/cache','',$url_path) . "\" title=\"View Full Size\"><img src=\"" . $url_path . "\" alt=\"" . $file_name . "\" /></a>",
								'href' => str_replace('/cache','',$url_path),
								'image_path' => $local_image_path,
								'file_name' => $file_name
								);
								$post_info = drizzo_get_the_post($post_id['post_id']);
								$image = array_merge($image, $post_info);
						}
					} else {
						echo "<p>" . mysql_error() . "</p>";
					}
				}
			} else {
				$image = false;
			}
		} else {
			$image_lookup = @mysql_query("SELECT `post_id` FROM `$drizzo_gallery` WHERE `file_path`='$local_image_path'");
			if(!mysql_errno() && @mysql_num_rows($image_lookup) > 0) {
				$url_path = str_replace(root_dir, '', $cache_image_path);
				$post_id = @mysql_fetch_assoc($image_lookup);
				$image = array(
					'ID' => $post_id['post_id'],
					'link' => "<a href=\"" . str_replace('/cache','',$url_path) . "\" title=\"View Full Size\"><img src=\"" . $url_path . "\" alt=\"" . $file_name . "\" /></a>",
					'href' => str_replace('/cache','',$url_path),
					'image_path' => $local_image_path,
					'file_name' => $file_name
					);
					$post_info = drizzo_get_the_post($post_id['post_id']);
					$image = array_merge($image, $post_info);
			} else {
				$url_path = str_replace(root_dir, '', $cache_image_path);
				$image = array(
					'link' => "<a href=\"/" . str_replace('/cache','',$url_path) . "\" title=\"View Full Size\"><img src=\"/" . $url_path . "\" alt=\"" . $file_name . "\" /></a>",
					'href' => str_replace('/cache','',$url_path),
					'image_path' => $local_image_path,
					'file_name' => $image,
					'title' => $image
					);
			}
		}
		return $image;
	} else {
		return false;
	}
	
}

function drizzo_gallery_albums($before = "<span class=\"album_thumb\">", $after = "</span>") {
	$this_folder = $_SERVER['REQUEST_URI'];
	$folder = $this_folder;
	$folder_path = explode('/', $folder);
	$folder_path = array_slice($folder_path, 1);
	$trail = "/";
	for($i = 0; $i < count($folder_path); $i++) {
		if($folder_path[$i] == "gallery") {
			$folder_path[$i] = drizzo_global_options('gallery_basename');
		}
		if($folder_path[$i] != '') {
			$trail .= $folder_path[$i] . "/"; 
		}
	}
	$subalbums = drizzo_gallery_get_the_folders($this_folder);
	if(count($subalbums) > 0) {
		foreach($subalbums as $subalbum) {
			$the_albums .= $before . "<a href=\"" . $trail . $subalbum . "\" title=\"" . $subalbum . "\">" . $subalbum . "</a>" . $after;
		}
		return $the_albums;
	} else {
		return false;
	}
}

function drizzo_gallery_images($before = "<span class=\"image_thumb\">", $after = "</span>") {
	$this_folder = str_replace("/" . drizzo_global_options('gallery_basename'),'/drizzo-files/gallery/', $_SERVER['REQUEST_URI']);
	$images = drizzo_gallery_get_the_images($this_folder);
	if(count($images) > 0) {
		foreach($images as $image) {
			if($thumb_path = drizzo_gallery_make_thumbnail($this_folder,$image)) {
				$href = drizzo_strip_file_extension(str_replace(array("drizzo-files/gallery","/thumbs"),array(drizzo_global_options('gallery_basename'),""),$thumb_path));
				if(drizzo_global_options('gallery_lightbox')) {
					$thumbs .= $before . "<a href=\"" . $href . "\" title=\"" . str_replace(array('.jpg','.jpeg','.png','.gif'),'',$image) . "\" rel=\"lightbox[gallery]\"><img src=\"" . $thumb_path . "\" alt=\"" . $image . "\" /></a>" . $after;
				} else {
					$thumbs .= $before . "<a href=\"" . $href . "\" title=\"" . $image . "\"><img src=\"" . $thumb_path . "\" alt=\"" . $image . "\" /></a>" . $after;
				}
			}
		}
		return $thumbs;
	} else {
		return false;
	}
}

function drizzo_gallery_make_thumbnail($folder,$file,$width = 50, $height = 50) {
	if($width == null) {
		$width = drizzo_global_options('gallery_thumb_width');
	}
	if($height == null) {
		$height = drizzo_global_options('gallery_thumb_height');
	}
	$new_folder = str_replace('/drizzo-files/gallery/','',$folder);
	$local_dir = str_replace("//","/",root_dir . "drizzo-files/gallery/thumbs/" . $new_folder);
	$image_and_path = str_replace("//","/",root_dir . $folder . "/" . $file);
	$thumb_and_path = $local_dir . "/" . $file;
	if(!file_exists($thumb_and_path) || $_POST['make_new_thumb'] == 1) {
		if(!file_exists($local_dir)) {
			$make_folder = drizzo_mkdir($local_dir);
		}
		if(is_writable($local_dir)) {
			list($width_orig, $height_orig, $type) = getimagesize($image_and_path);
			if($width_orig > $height_orig) {
				$scale = $width_orig/$width;
				$x = round((($width_orig - $height_orig) / $scale) / 2);
				$y = 0;
			} elseif($width_orig < $height_orig) {
				$scale = $height_orig/$height;
				$x = 0;
				$y = round((($height_orig - $width_orig) / $scale) / 2);
			} else {
				$x = 0;
				$y = 0;
			}
			$ratio_orig = $width_orig/$height_orig;
			if ($width/$height < $ratio_orig) {
				$new_height = $height;
				$new_width = round($height*$ratio_orig);
			} else {
				$new_height = round($width/$ratio_orig);
				$new_width = $width;
			}
			if($type == 2) {
				$thumb = imagecreatetruecolor($width,$height);
				$original = imagecreatefromjpeg($image_and_path);
				imagecopyresampled($thumb, $original, -$x, -$y, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
				$thumb_check = imagejpeg($thumb, $thumb_and_path, 100);
				imagedestroy($thumb);
				if($thumb_check) {
					$thumb_path = domain . "drizzo-files/gallery/thumbs/" . $file;
					return $thumb_path;
				} else {
					return false;
				}
			} elseif($type == 3) {
				$thumb = imagecreatetruecolor($width,$height);
				$original = imagecreatefrompng($image_and_path);
				imagecopyresampled($thumb, $original, -$x, -$y, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
				$thumb_check = imagepng($thumb, $thumb_and_path, 100);
				imagedestroy($thumb);
				if($thumb_check) {
					$thumb_path = domain . "drizzo-files/gallery/thumbs/" . $file;
					return $thumb_path;
				} else {
					return false;
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	} else {
		$thumb_path = domain . str_replace(root_dir,"",$thumb_and_path);
		return $thumb_path;
	}
}

function drizzo_gallery_exif_info($image_path = null) {
	if($image_path) {
		$exif = exif_read_data($image_path);
		return $exif;
	} else {
		return false;
	}
}

function drizzo_gallery_breadcrumbs($seperator = " &raquo; ") {
	$path = $_SERVER['REQUEST_URI'];
	$crumbs = pathinfo($path);
	$current = $crumbs['basename'];
	$trail = explode('/', $crumbs['dirname']);
	$trail = array_slice($trail, 1);
	if(count($trail) > 0) {
		$prev = null;
		for($i = 0; $i < count($trail); $i++) {
			if($trail[$i] != '') {
				$breadcrumbs .= "<a href=\"/";
				if($trail[$i] != $prev && $prev != null) {
					$breadcrumbs .= $prev . "/";
				}  
				$breadcrumbs .= $trail[$i] . "\" title=\"" . $trail[$i] . "\" class=\"breadcrumb\">" . $trail[$i] . "</a>" . $seperator;
				$prev = $trail[$i];
			}
		}
	}
	$breadcrumbs .= $current;
	return $breadcrumbs;
}

function drizzo_strip_file_extension($paths) {
	if(is_array($paths)) {
		foreach($paths as $path) {
			$path = str_replace('.' . pathinfo($path, PATHINFO_EXTENSION), '', $path);
			$new_path[] = $path;
		}
		return $new_path;
	} else {
		return str_replace('.' . pathinfo($paths, PATHINFO_EXTENSION), '', $paths);
	}
}

function drizzo_gallery_previous_and_next_image() {
	$link = null;
	$directory = dirname($_SERVER['REQUEST_URI']);
	$directory_local = str_replace(drizzo_global_options('gallery_basename'),"drizzo-files/gallery",$directory);
	$dir_list = drizzo_gallery_get_the_images($directory_local);
	$dir_list = drizzo_strip_file_extension($dir_list);
	$key = array_search(basename($_SERVER['REQUEST_URI']), $dir_list);
	$image_count = count($dir_list);
	if($key > 0 && $key < $image_count) {
		$link['previous'] = $directory . "/" . $dir_list[$key - 1];
		$link['next'] = $directory . "/" . $dir_list[$key + 1];
	} elseif($key == 0 && $image_count > 1) {
		$link['previous'] = $directory . "/" . $dir_list[$image_count];
		$link['next'] = $directory . "/" . $dir_list[$key + 1];
	} elseif ($key == $image_count && $image_count > 1) {
		$link['previous'] = $directory . "/" . $dir_list[$key - 1];
		$link['next'] = $directory . "/" . $dir_list[0];
	} else {
		$link = false;
	}
	return $link;
}

function drizzo_gallery_previous_image_link($before = null) {
	$links = drizzo_gallery_previous_and_next_image();
	if($links) {
		$previous = "<a href=\"" . $links['previous'] . "\" title=\"Previous Image\" id=\"previous_link\">" . $before .  pathinfo($links['previous'], PATHINFO_BASENAME) . "</a>";
		return $previous;
	}
}

function drizzo_gallery_next_image_link($after = null) {
	$links = drizzo_gallery_previous_and_next_image();
	if($links) {
		$next = "<a href=\"" . $links['next'] . "\" title=\"Next Image\" id=\"next_link\">" . pathinfo($links['next'], PATHINFO_BASENAME) . $after . "</a>";
		return $next;
	}
}

function drizzo_gallery_show_previous_and_next_image($before = null, $after = null, $seperator = null) {
	$links = "<div id=\"previous_and_next\">\n";
	$links .= drizzo_gallery_previous_image_link($before);
	$links .= $seperator;
	$links .= drizzo_gallery_next_image_link($after);
	$links .="</div>\n";
	return $links;
}

function drizzo_gallery_show_the_image() {
	if(drizzo_gallery_is_image()) {
		$image .= "<div id=\"gallery_image\">\n";
		$the_image = drizzo_gallery_image();
		$image .= "<h2><a href=\"" . $the_image['href'] . "\" title=\"" . $the_image['title'] . "\">" . drizzo_strip_file_extension($the_image['title']) . "</a></h2>\n";
		$image .= "<div id=\"gallery_img\">" . $the_image['link'] . "</div>\n";
		$image .= drizzo_gallery_show_previous_and_next_image('&laquo; ', ' &raquo;') . "<br class=\"clear\" />";
		$image .= "</div>\n";
		return $image;
	} else {
		return false;
	}
}

function drizzo_gallery_show_albums() {
	if(drizzo_gallery_albums()) {
		$albums .= "<div id=\"gallery_albums\">\n";
		$albums .= drizzo_gallery_albums() . "\n";
		$albums .= "</div>\n";
		$albums .= "<br class=\"clear\" />\n";
		$albums .= "<hr />\n";
		$albums .= "<br class=\"clear\" />\n";
		return $albums;
	} else {
		return false;
	}
}

function drizzo_gallery_show_the_thumbs() {
	if(drizzo_gallery_images()) {
		$thumbs .= "<div id=\"gallery_thumbs\">\n";
		$thumbs .= drizzo_gallery_images() . "\n";
		$thumbs .= "</div>\n";
		$thumbs .= "<br class=\"clear\" />\n";
		return $thumbs;
	} else {
		return false;
	}
}

function drizzo_gallery_show_the_thumbnails() {
	return drizzo_gallery_show_the_thumbs();
}

function drizzo_gallery_show_the_breadcrumbs() {
	$breadcrumbs .= drizzo_gallery_breadcrumbs() . "\n";
	$breadcrumbs .= "<hr />\n";
	return $breadcrumbs;
}

function drizzo_gallery_image_comments() {
	if(drizzo_gallery_is_image()) {
		$the_post = drizzo_gallery_image();
		$post_id = $the_post['ID'];
		$comments_uri = drizzo_theme('directory') . "comments.php?post_id=" . $post_id;
		$comments_string = file_get_contents($comments_uri);
		return $comments_string;
	} else {
		return false;
	}
}

function drizzo_gallery() {
	$gallery = null;
	if(drizzo_gallery_show_the_breadcrumbs()) {
		$gallery .= drizzo_gallery_show_the_breadcrumbs();
	}
	if(drizzo_gallery_show_the_image()) {
		$gallery .= drizzo_gallery_show_the_image();
	}
	if(drizzo_gallery_show_albums()) {
		$gallery .= drizzo_gallery_show_albums();
	}
	if(drizzo_gallery_show_the_thumbnails()) {
		$gallery .= drizzo_gallery_show_the_thumbnails();
	}
	if(!drizzo_gallery_show_the_image() && !drizzo_gallery_show_albums() && !drizzo_gallery_show_the_thumbnails()) {
		$gallery = "<p>The item you are looking for cannot be found</p>\n";
	}
	return $gallery;
}

function drizzo_gallery_image_permalink($post_id = null) {
	global $drizzo_gallery;
	$image_lookup = @mysql_query("SELECT `path` FROM `$drizzo_gallery` WHERE `post_id`='$post_id'");
	if(!mysql_error() && @mysql_num_rows($image_lookup) > 0) {
		$image_path = mysql_fetch_array($image_lookup);
		return domain . str_replace(array(root_dir,"//",'drizzo-files/gallery',"." . pathinfo($image_path['path'], PATHINFO_EXTENSION)), array('',"/",drizzo_global_options('gallery_basename'),'',"/"), $image_path['path']);
	} else {
		return false;
	}
}

function drizzo_gallery_list() {
	global $drizzo_gallery;
	$images_lookup = @mysql_query("SELECT * FROM `$drizzo_gallery` ORDER BY `path`");
	if(!mysql_errno() && @mysql_num_rows($images_lookup) > 0) {
		while($image = mysql_fetch_assoc($images_lookup)) {
			$images[] = $image;
		}
	}
	$image = null;
	$list = "<table id=\"media_list\">\n";
	$list .= "\t<tr id=\"first\">\n";
	$list .= "\t\t<th>Title</th><th>Tags</th><th>Created</th><th>Comments</th><th class=\"center\">Author</th><th class=\"narrow center\" colspan=\"2\">Action</th>\n";
	$list .= "\t</tr>";
	if($images) {
		foreach($images as $image) {
			$the_post = drizzo_get_the_post($image['post_id']);
			$album = dirname(str_replace(array(root_dir,'drizzo-files/gallery/'),'',$image['path']));
			if($album == '.') {
				$album = null;
			}
			if($album != $prev_album) {
				$list .= "\t<tr>\n";
				$list .= "\t\t<td colspan=\"7\" class=\"file folder\"><strong>$album</strong></td>\n";
				$list .= "\t</tr>\n";
			}
			if($the_post['author'] > 0) {
				$author = drizzo_user_info($the_post['author'],'nice_name');
			} else {
				$author = "via FTP";
			}
			$list .= "\t<tr>\n";
			$list .= "\t\t<td><a href=\"" . drizzo_gallery_image_permalink($image['post_id']) . "\">" . $the_post['title'] . "</a></td><td>" . $the_post['tags'] . "</td><td>" . $the_post['posted_date'] . "</td><td class=\"narrow center\">" . $the_post['comment_count'] . "</td><td class=\"center\">" . $author . "</td>";
			if(drizzo_post_permissions_check($the_post['ID'])) {
				$list .= "<td><a href=\"gallery.php?action=edit&amp;id=$the_post[ID]&amp;item=" . rtrim($image['path'],"/") . "\" title=\"Edit this Image Post\" class=\"edit_link\"><span>Edit</span></a></td><td><a href=\"gallery.php?action=delete&amp;id=$the_post[ID]&amp;item=" . rtrim($image['path'],"/") . "\" title=\"Delete this Image Post\" class=\"delete_link\"><span>Delete</span></a></td>\n";
			} else {
				$list .= "<td></td><td></td>\n";
			}
			$list .= "\t</tr>\n";
			unset($the_post);
			$prev_album = $album;
		}
	} else {
		$list .= "\t<tr>\n";
		$list .= "\t\t<td colspan=\"6\">There are no images found in the database.  It is possible that images have been uploaded by FTP but not yet viewed.</td>\n";
		$list .= "\t</tr>\n";
	}
	$list .= "</table>";
	return $list;
}
?>
